#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#include<arpa/inet.h>
#include<pthread.h>

//UDP socket实现网络通信，本生支持高并发

int main(void)
{
    struct sockaddr_in serv_addr,clit_addr;
    socklen_t clit_len;
    int sockfd;//取代tcp 中的lfd
    char buf[1024], straddr[1024];
    sockfd=socket(AF_INET,SOCK_DGRAM,0);
    memset(&serv_addr,0,sizeof(struct sockaddr_in));

    serv_addr.sin_family=AF_INET;
    serv_addr.sin_port=htons(9999);
    serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
    
    bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));

    printf("accepting connect!!!!\n");
    int ndata;
    while(1)
    {
        clit_len=sizeof(clit_addr);
       ndata=recvfrom(socket,buf,1024,0,(struct sockaddr*)&clit_addr,&clit_len);//从client读数据——》read(TCP)
       printf("client is connect! received from %s at port %d!\n",
              inet_ntop(AF_INET,&clit_addr.sin_addr.s_addr,straddr,sizeof(straddr)),ntohs(clit_addr.sin_port));

       for(int i=0;i<ndata;i++)
       {
           buf[i]=toupper(buf[i]);
       }

       //将服务器完成数据转换后重新写回client
       ndata=sendto(sockfd,buf,ndata,0,(struct sockaddr*)&clit_addr,clit_len);

       close(sockfd);
    }

    
}
